<template>
  <div>
    <el-radio-group v-model="filters.payStatus" style="margin-bottom: 30px;" @change="getSiteList(1)">
      <el-radio-button label="">{{ $t('message.qbdd') }}</el-radio-button>
      <el-radio-button label="0">{{ $t('message.wzf') }}<span v-if="num> 0">{{ num > 99 ?'99+': num }}</span></el-radio-button>
      <el-radio-button label="1">{{ $t('message.gqwf') }}</el-radio-button>
      <el-radio-button label="2">{{ $t('message.yqx') }}</el-radio-button>
      <el-radio-button label="3">{{ $t('message.ypay') }}</el-radio-button>
      <!-- <el-radio-button label="4">{{ $t('message.tkz') }}</el-radio-button> -->
      <el-radio-button label="5">{{ $t('message.tkcg') }}</el-radio-button>
    </el-radio-group>
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @handleQuery="getSiteList(1)" @clear="clearList" />
    <el-table ref="table" v-loading="listLoading" :data="list" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-table doumee-element-tableb">
      <el-table-column align="center" :label="$t('message.ddh')" prop="orderId" width="220">
        <template slot-scope="scope">
          <span class="ckxqBtn" @click="orderBtn(scope.row)"> {{ scope.row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.xmlx')" prop="itemName" show-overflow-tooltip min-width="100" />
      <el-table-column align="center" :label="$t('message.ddxq')" min-width="400" prop="orderInfo" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.ddzsj')" prop="orderAllTime" show-overflow-tooltip min-width="120" />
      <el-table-column align="center" :label="$t('message.yjzj')" prop="allPrice" show-overflow-tooltip min-width="100" />
      <el-table-column align="center" :label="$t('message.zhzj')" prop="realPrice" show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          {{ scope.row.realPrice || scope.row.realPrice === 0 || scope.row.realPrice === '0' ? scope.row.realPrice : scope.row.memberPrice || scope.row.memberPrice === 0 || scope.row.memberPrice === '0' ? scope.row.memberPrice :scope.row.allPrice }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.tkje')" prop="refundMoney" show-overflow-tooltip min-width="100" />
      <el-table-column align="center" :label="$t('message.ddly')" show-overflow-tooltip prop="channelType" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.channelTypeName }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.zffs')" prop="payMethed" show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          {{ scope.row.payMethodName || '-' }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.ydr')" min-width="160" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.userType == '0'">{{ scope.row.memberName? scope.row.memberName + ' ' : '' }} {{ scope.row.memberPhone || '' }}</span>
          <span v-if="scope.row.userType == '1'">{{ scope.row.userName? scope.row.userName + ' ' : '' }} {{ scope.row.userPhone || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.ydfs')" prop="channelType" show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          {{ scope.row.userType == "0" ? $t('message.hy') : $t('message.sk') }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.bz')" min-width="200" prop="remarks" show-overflow-tooltip />
      <el-table-column align="center" :label="$t('message.czy')" min-width="120" show-overflow-tooltip prop="creatorName" />
      <el-table-column align="center" :label="$t('message.createTime')" show-overflow-tooltip min-width="160" prop="createTime" />
      <el-table-column align="center" :label="$t('message.paytime')" show-overflow-tooltip min-width="160" prop="payTime" />
      <el-table-column :label="$t('message.ddzt')" prop="sort" min-width="100" show-overflow-tooltip align="center" fixed="right">
        <template slot-scope="scope">
          {{ scope.row.statusName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.caozuo')" :width="$i18n.locale === 'ZH'? 250 : 400" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button v-if="scope.row.status == 0 && meta.indexOf('SiteOrderPayCon') > -1" v-preventReClick type="text" @click="paymentShow(scope.row)">{{ $t('message.jxzf') }}</el-button>
            <el-button v-if="scope.row.status == 0 && meta.indexOf('SiteOrderPayCon') > -1" v-preventReClick type="text" @click="addShow(scope.row)">{{ $t('message.zjdc') }}</el-button>
            <el-popover :key="`popover-${scope.row.id}`" placement="bottom" width="120" class="el-pop-btns" trigger="hover">
              <div>
                <div class="moreBtn" @click.stop="getOrderType(scope.row.orderId)">{{ $t('message.cxzfzt') }}</div>
                <div v-if="meta.indexOf('SiteOrderPayCan') > -1" class="moreBtn" @click.stop="cancelBtn(scope.row)">{{ $t('message.qxyd') }}</div>
              </div>
              <el-button v-if="scope.row.status == 0" slot="reference" type="text" class="moreBtnShow">{{ $t('message.more') }}<i class="el-icon-caret-bottom primaryColor" /></el-button>
            </el-popover>
            <el-button v-if="meta.indexOf('SiteOrderPayCan') > -1 && scope.row.status == 3" v-preventReClick type="text" @click="cancelBtn(scope.row)">{{ $t('message.cdtd') }}</el-button>
            <!-- <el-button
              v-if="scope.row.status == 3 && meta.indexOf('SiteOrderCan') > -1"
              v-preventReClick
              type="text"
              @click="unsubscribeOrderBtn(scope.row)"
            >{{ $t('message.cdtd') }}</el-button> -->
            <el-button v-if="scope.row.status == 3" v-preventReClick type="text" @click="printOrder(scope.row.orderId)">{{ $t('message.dyxp') }}</el-button>
            <span v-if="scope.row.status == 2 || scope.row.status > 3 || scope.row.status == 1">-</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations :total="total" :page="pagination.page" :page-size="pagination.rows" @current-change="getSiteList" @SizeChange="handleSizeChange" />
    <orderDialog ref="child" @orderSuccess="getSiteList()" />
    <areaSellOrderDetail ref="areaSellOrderDetail" />
    <Replacement ref="replacement" @replacementList="replacementList" />
    <closeReserve ref="closeReserve" @closeSccess="getSiteList()" />
    <printTem v-if="isPrint" ref="printTemRef" />
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import {
  printOrder,
  getChannelType,
  orderType,
  getProjectList,
  addReserves, allConfigList, siteOrderListPc, unsubscribeOrder, deleteUserReserveRecord
} from '@/api'
import orderDialog from '@/components/order'
import QueryForm from '@/components/QueryForm'
import areaSellOrderDetail from '@/components/areaSellOrderDetail.vue'
import Replacement from '@/components/replacement.vue'
import closeReserve from '../../closeReserve.vue' // 取消
import printTem from '@/components/printTem'

import store from '@/store'
export default {
  components: {
    orderDialog, QueryForm, areaSellOrderDetail, Replacement, closeReserve, printTem
  },
  data () {
    return {
      isPrint: false,
      modalDialog: store.getters.dialog,
      authCode: '',
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: this.$t('message.ddbh'),
          clearable: true
        }, {
          filed: 'userInfo',
          type: 'input',
          label: this.$t('message.khxx'),
          placeholder: this.$t('message.qsr') + this.$t('message.hy4'),
          clearable: true
        }, {
          filed: 'channelType',
          type: 'select',
          label: this.$t('message.ddly'),
          clearable: true,
          options: []
        }, {
          filed: 'payMethod',
          type: 'select',
          label: this.$t('message.zflx'),
          clearable: true,
          options: []
        },
        {
          filed: 'itemId',
          type: 'select',
          label: this.$t('message.xmlx'),
          clearable: true,
          options: []
        },
        {
          filed: 'time',
          label: this.$t('message.createTime'),
          type: 'daterange',
          clearable: true
        },
        {
          filed: 'payTime',
          label: this.$t('message.paytime'),
          type: 'daterange',
          clearable: true
        }
        ],
        online: true
      },
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      num: 0,
      total: 0,
      allPayMethedList: [],
      filters: {
        payStatus: ''
      },
      listLoading: false,
      loading: false,
      meta: [],
      orderId: '',
      siteIds: [],
      siteList: [],
      status: ''
    }
  },
  created () {
    this.pdgj()
    this.getChannel()
    this.getProject()
    this.meta = this.$route.meta.buttons || []
  },
  methods: {
    getChannel () {
      getChannelType({ param: { code: 'CHANNEL_SITE' } }).then(res => {
        this.queryFormConfig.formItems[2].options = res.recordList.map(item => {
          return {
            label: item.name,
            value: item.value
          }
        })
      })
    },
    getProject () {
      getProjectList({ param: { status: '1', venueId: sessionStorage.getItem('venueId') } }).then(res => {
        this.queryFormConfig.formItems[4].options = res.recordList.map(item => {
          return {
            label: item.projectName,
            value: item.id
          }
        })
      })
    },
    nameWithPayMethod (payM) {
      const temp = this.allPayMethedList.find((item) => item.value === payM)
      return temp ? temp.name : '-'
    },
    replacementList (e) {
      this.siteIds = e.siteIds
      const that = this
      if (e.siteIds && e.siteIds.length > 0) {
        this.$confirm(this.$t('message.qrzjdctc'), this.$t('message.ts'), {
          confirmButtonText: this.$t('message.qd'),
          cancelButtonText: this.$t('message.qx'),
          type: 'warning',
          callback: () => { },
          beforeClose: (action, ctx, close) => {
            if (action !== 'confirm') {
              close()
              return
            }
            ctx.confirmButtonLoading = true
            addReserves({ param: { orderId: that.orderId, siteIds: that.siteIds } }).then((res) => {
              ctx.confirmButtonLoading = false
              close()
              if (res.errorCode === '000000') {
                that.$message.success(this.$t('message.zjdccg'))
                that.getSiteList()
              }
            })
              .catch(() => { ctx.confirmButtonLoading = false })
          }
        }).finally(() => { })
      }
    },
    addShow (row) {
      this.orderId = row.orderId
      this.$refs.replacement.showBtn(row.siteList[0].day, row.siteList[0].projectId, row.siteList, 1)
    },
    handleSizeChange (e) {
      this.pagination.rows = e
      this.getSiteList(1)
    },
    getOrderType (orderId) {
      orderType({
        param: {
          orderId
        }
      })
        .then((res) => {
          const str = res.record.msg
          if (res.errorCode === '000000') {
            if (res.record.code === '0') {
              this.$message.success(str)
              this.getSiteList()
            } else if (res.record.code === '2') {
              this.$message.info(str)
            } else {
              this.$message.error(str)
              this.getSiteList()
            }
          }
        })
    },
    printOrder (id, refundOrderId) {
      const venueId = sessionStorage.getItem('venueId')
      this.isPrint = true
      printOrder({
        param: {
          venueId,
          templateCode: refundOrderId ? 'SITE_REFUND_TPML' : 'SITETPML',
          workId: id,
          refundOrderId
        }
      })
        .then(res => {
          if (res.errorCode === '000000') {
            if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
              console.log('---')
              res.record.dataList.forEach(item => {
                this.$nextTick(() => {
                  this.$refs.printTemRef.obj = { ...item }
                  setTimeout(() => {
                    this.$refs.printTemRef.print()
                  }, 300)
                })
                setTimeout(() => {
                  this.isPrint = false
                }, 500)
              })
            } else {
              this.isPrint = false
            }
          }
        }).catch(() => {
          this.isPrint = false
        })
    },
    pdgj () {
      allConfigList({ param: { type: '2', code: '1' } })
        .then(res => {
          if (res.errorCode !== '000000') return
          const arr = res.recordList
          arr.forEach(e => {
            e.label = e.name
          })
          this.queryFormConfig.formItems[3].options = arr
          this.allPayMethedList = arr
        })
        .catch(err => {
          console.log(err)
        })
    },
    clearList () {
      this.filters = { payStatus: '' }
      // this.$set(this.filters, 'time', [parseTime(new Date()).slice(0, 10), parseTime(new Date()).slice(0, 10)])
      this.getSiteList(1)
    },
    getSiteList (page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      if (filters.time && filters.time.length > 0) {
        filters.startDate = filters.time[0] + ' 00:00:00'
        filters.endDate = filters.time[1] + ' 23:59:59'
      } else {
        filters.startDate = ''
        filters.endDate = ''
      }
      if (filters.payTime && filters.payTime.length > 0) {
        filters.payTimeStart = filters.payTime[0] + ' 00:00:00'
        filters.payTimeEnd = filters.payTime[1] + ' 23:59:59'
      } else {
        filters.payTimeStart = ''
        filters.payTimeEnd = ''
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      siteOrderListPc({ pagination, param: { venueId, ...filters } }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.total = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getSiteList(Math.ceil(res.totalCount / pagination.rows))
          }
          this.$refs.table.doLayout()
        }
      }).catch(() => {
        this.listLoading = false
      })
      // siteOrderListPc({ pagination: {
      //   page: 1,
      //   rows: 1
      // }, param: { venueId, payStatus: '0' }}).then(res => {
      //   if (res.errorCode === '000000') {
      //     this.num = res.totalCount
      //   }
      // }).catch(() => {})
    },
    deletelBtn (e) {
      deleteUserReserveRecord({ param: { reserveAndOrderId: e.id } })
        .then(res => {
          if (res.errorCode === '000000') {
            this.$message.success(this.$t('message.delcg'))
            this.getSiteList()
          }
        })
    },
    cancelBtn (e) {
      this.$refs.closeReserve.cancelBtn(e, [])
    },
    unsubscribeOrderBtn (e) {
      const that = this
      this.$confirm(this.$t('message.cdtdtc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => { },
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          unsubscribeOrder({ param: { reserveAndOrderId: e.id } }).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.cdtdcg'))
              that.getSiteList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => { })
    },
    changePriceClick () {
      if (this.change === 0) {
        this.change = 1
      } else {
        this.change = 0
      }
    },
    paymentShow (cnt) {
      this.$refs.child.continuePay(cnt, 'areaSellOrder')
    },
    changePayMothed (item) {
      if (this.payMethod === item.value) {
        return
      }
      this.integralUse = '0'
      this.payMethod = item.value
      this.getOrderPrice()
    },
    orderBtn (row) {
      this.$refs.areaSellOrderDetail.getOrderDetail(row.id)
      // siteOrderInfo({ param: { businessId: row.id }}).then((res) => {
      //   if (res.errorCode === '000000') {
      //     this.$refs.areaSellOrderDetail.showDetail(res.record)
      //   }
      // })
    }

  }
}
</script>

